<!doctype html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>画廊</title>
    <style>
        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
            overflow-x: hidden;
        }
        /* 添加导航栏的样式 */
        nav {
            background-color: #468ef3; /* 导航栏背景颜色 */
            padding: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-radius: 10px;
            width: 90%;
            margin: 20px auto;
        }

        nav a {
            color: white; /* 链接的文字颜色 */
            text-decoration: none; /* 去掉下划线 */
            padding: 10px 20px;
        }

        nav a:hover {
            background-color: #669fee; /* 悬停时背景颜色变化 */
            border-radius: 5px;
        }
        .image-container video {
            max-width: 100%;
            max-height: 300px;
            margin-bottom: 5px; /* 让视频和图片之间保持相同的间距 */
        }

        .image-container {
            /* border: 2px solid black;
            padding: 5px;
            margin: 5px; */
            
            width: 90%;
            margin: 25px auto;
            display: flex;
            flex-wrap: wrap;
            background-color: #ffffffc3;
            border-radius: 5px;
            align-items: center; /* 垂直居中 */
            position: relative; /* 确保评论的正确定位 */
        }
        .image-container img {
            max-width: 70%;
            max-height: 500px;
            margin-bottom: 10px; /* 在图片之间增加一些间距 */
            margin-top: 15px;
            margin-left: 15px;
        }
        .comment-container {
            display: none;
            position: absolute;
            top: 0;
            right: 0; /* 向右调整定位 */
            padding: 5px;
            max-width: 150px; /* 限制评论容器的宽度 */
        }
        .comment-container input[type="text"] {
            width: calc(100% - 30px);
            margin-right: 5px;
            margin-bottom: 5px;
            background-color: #ffffffa0;
            border-radius: 5px;
            border-color: #ffffffa0;
            height: 15px;
        }
        .comment-container button {
            background-color: #ffffffa0;
            border-radius: 5px;
            border-color: #ffffffa0;
            width: 80px;
        }
        .pagination {
            margin-top: 20px;
            display: flex;
            justify-content: center; /* 将按钮水平居中 */
        }

        .pagination button {
            font-size: 16px; /* 修改字体大小 */
            padding: 10px 20px; /* 增加内边距 */
            /* border-radius: 5px; 圆角边框 */
            background-color: #ffffffc3;
            margin: 0 25px;
        }


        .commentSubmission {
            display: none; 
        }

        .commentsFromBackend {
            display: block; 
        }

        body
        {
            background-image: url("background.png");
            background-size: cover;
            background-position-x: center;
            background-repeat: no-repeat;
            height: 100vh;
            width: 100vw;
        }

        footer {
            background-color: #468ef3; /* 底栏背景颜色 */
            color: white; /* 底栏文字颜色 */
            text-align: center; /* 文本居中 */
            padding: 10px 0; /* 上下内边距 */
            margin-top: auto; /* 将底栏推到页面底部 */
        }

        .footer-text {
            font-size: smaller;
            line-height: 2;
            color: #bdd2f0;
        }

        .footer-text a {
            line-height: 2;
            color: #bdd2f0;
        }

        @media screen and (max-width: 768px) {
            .image-container img {
                max-width: 70%;
                max-height: 500px;
                margin-top: 15px;
                margin-left: 15px;
            }

            .comment-container {
                display: none; /* 保持隐藏状态 */
                position: relative; /* 改为相对定位 */
                bottom: 0; /* 使其位于父模块底部 */
                padding: 5px;
                max-width: 150px; /* 限制评论容器的宽度 */
                margin-top: 10px; /* 可选：为上方添加一些间距 */
                margin-bottom: 20px;
            }
        }
    </style>

</head>
<body>
    <nav>
        <a href="/">首页</a>
        <a href="/c15">政治</a>
        <a href="/g">画廊</a>
    </nav>
    
    <div id="gallery">
        <!-- 图片将在此插入 -->
    </div>

    <div class="pagination">
        <button id="prevPageBtn" disabled>上一页</button>
        <button id="nextPageBtn">下一页</button>
    </div>

    <!-- 从后端检索的评论的容器 -->
    <div id="commentsFromBackend" style="display: none;"></div>

    <!-- 评论提交的容器 -->
    <div id="commentSubmission" style="display: none;"></div>

    <script>
        let imagesPerPage = 1000;
        let currentPage = 0;

        function toggleCommentContainer(commentContainer) {
            const currentDisplay = commentContainer.style.display;
            commentContainer.style.display = currentDisplay === 'none' ? 'block' : 'none';
        }

        fetch('/list-images2')
            .then(response => response.json())
            .then(images => {
                loadPage(images, currentPage); // 加载第一页的图片
            });

        function loadPage(images, pageNumber) {
            currentPage = pageNumber; // 更新当前页
            const startIndex = pageNumber * imagesPerPage;
            const endIndex = Math.min((pageNumber + 1) * imagesPerPage, images.length);
            loadImages(images, startIndex, endIndex);
            // 根据当前页启用或禁用分页按钮
            document.getElementById('prevPageBtn').disabled = pageNumber === 0;
            document.getElementById('nextPageBtn').disabled = (pageNumber + 1) * imagesPerPage >= images.length;
        }

        function loadImages(images, startIndex, endIndex) {
            const gallery = document.getElementById('gallery');
            loadNextImage(images, startIndex, endIndex, gallery);
        }

        function loadNextImage(images, currentIndex, endIndex, gallery) {
            if (currentIndex < endIndex) {
                const imageFilename = images[currentIndex];
                createImage(imageFilename, currentIndex, gallery, () => {
                    loadNextImage(images, currentIndex + 1, endIndex, gallery);
                });
            }
        }

        function createImage(mediaFilename, index, gallery, callback) {
            const mediaContainer = document.createElement('div');
            mediaContainer.classList.add('image-container');

            let mediaElement;
            const fileExtension = mediaFilename.split('.').pop().toLowerCase();

            if (['jpg', 'jpeg', 'png', 'gif'].includes(fileExtension)) {
                // Create an image element
                mediaElement = document.createElement('img');
mediaElement.loading = 'lazy';

                mediaElement.onload = callback;
                mediaElement.src = `/15/${mediaFilename}`;
            
            } else if (['mp4', 'webm', 'ogg'].includes(fileExtension)) {
                // 创建视频元素
        mediaElement = document.createElement('video');
        mediaElement.controls = true; // 显示控制按钮

        // 使用 IntersectionObserver 懒加载视频
        const observer = new IntersectionObserver((entries) => {
            entries.forEach((entry) => {
                if (entry.isIntersecting) {
                    mediaElement.src = `/15/${mediaFilename}`;
                    mediaElement.addEventListener('canplay', callback);
                    observer.unobserve(mediaElement); // 加载完成后停止观察
                }
            });
        });
        observer.observe(mediaElement);
            } else {
                console.error('Unsupported media type');
                return;
            }
            mediaContainer.appendChild(mediaElement);
            const filename = mediaFilename;

            const commentContainer = document.createElement('div');
            commentContainer.classList.add('comment-container');

            const commentInput = document.createElement('input');
            commentInput.type = 'text';
            commentInput.placeholder = '输入评论';
            commentInput.id = `comment-${index}`;

            const submitButton = document.createElement('button');
            submitButton.textContent = '提交评论';
            submitButton.onclick = () => submitComment(index, commentInput, filename);

            const commentsParagraph = document.createElement('p');
            commentContainer.appendChild(commentsParagraph);

           fetch(`/get-comments/${filename}`)
    .then(response => response.text())
    .then(comments => {
        commentsParagraph.innerHTML = comments.replace(/\n/g, '<br>');  // 替换换行符为 <br> 标签
        commentContainer.style.display = 'block'; // 总是显示评论
        // 将后端的评论存储在单独的容器中
        document.getElementById('commentsFromBackend').appendChild(commentContainer.cloneNode(true));
    });


            commentContainer.appendChild(commentInput);
            commentContainer.appendChild(submitButton);

            mediaElement.addEventListener('click', () => {
                toggleCommentContainer(commentContainer);
            });

            // 将评论提交元素存储在单独的容器中
            document.getElementById('commentSubmission').appendChild(commentContainer.cloneNode(true));

            mediaContainer.appendChild(mediaElement);
            mediaContainer.appendChild(commentContainer);
            gallery.appendChild(mediaContainer);
        }


        function refreshGallery() {
            const gallery = document.getElementById('gallery');
            gallery.innerHTML = ''; // 清除现有的图片
            fetch('/list-images')
                .then(response => response.json())
                .then(images => {
                    loadPage(images, currentPage);
                });
        }



function submitComment(index, commentInput, filename) {
    const comment = commentInput.value.trim(); // 获取评论文本
    const validRegex = /^[a-zA-Z\u4e00-\u9fa5\s，。？！：；、,.!?()（）“”‘’—–\-]+$/;


    if (validRegex.test(comment)) {
        // 移除文件扩展名
        const extensionIndex = filename.lastIndexOf('.');
        const filenameWithoutExtension = filename.substring(0, extensionIndex);

        // 将评论和图片索引以及文件名发送到服务器
        fetch('/upload-comment', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ filename: filenameWithoutExtension, comment: comment })
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('评论上传成功！');
                    refreshGallery(); // 刷新页面
                } else {
                    alert('评论上传失败。');
                }
            })
            .catch(error => {
                console.error('错误：', error);
            });
    } else {
        alert('评论只能包含中英文字符。请重新输入。');
    }
}


        document.getElementById('nextPageBtn').addEventListener('click', () => {
            const gallery = document.getElementById('gallery');
            gallery.innerHTML = ''; // 清除现有的图片
            fetch('/list-images')
                .then(response => response.json())
                .then(images => {
                    loadPage(images, currentPage + 1); // 加载下一页
                });
        });

        document.getElementById('prevPageBtn').addEventListener('click', () => {
            const gallery = document.getElementById('gallery');
            gallery.innerHTML = ''; // 清除现有的图片
            fetch('/list-images')
                .then(response => response.json())
                .then(images => {
                    loadPage(images, currentPage - 1); // 加载上一页
                });
        });
    </script>

    <footer>
        <img src="footer.png" alt="Footer Image" style="display: block; margin: 0 auto; max-width: 60%; max-height: 125px;"/>
        <div class="footer-text">
            Made with ❤️ by dev group:
            <br>
            <a href="https://space.bilibili.com/562001644?spm_id_from=..0.0">Steven_Lee_147</a>, 
            <a href="https://space.bilibili.com/1718299194?spm_id_from=..0.0">CharlesZiy</a>, 
            Fitten Code, ChatGPT, and Github Copilot.
            <br>
            友链：
            <a href="https://space.bilibili.com/693772585?spm_id_from=..0.0">某知名英语老师</a> |
            <a href="https://memoir.rdfz.app/">黄庄回响集</a>

        </div>
    </footer>
</body>
</html> 